﻿//===============================================================================
// Magic OQL
//===============================================================================
// Copyright ?Magic Thought Corporation. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// Richie (http://www.cnblogs.com/RicCC)
// March 8, 2008
//===============================================================================

using Antlr.Runtime;
using Antlr.Runtime.Tree;

namespace SQLAnalyticLibrary.Expressions
{
    /// <summary>
    /// Select clause
    /// </summary>
    public class GroupByClause : CombinedKeywords
    {
        #region constructors
        public GroupByClause(Expression node)
            : base(node.Token, string.Empty, false, null, false, new int[] { OQLParser.GROUP, OQLParser.BY })
        {
        }
        public GroupByClause(IToken t)
            : base(t, string.Empty, false, null, false, new int[] { OQLParser.GROUP, OQLParser.BY })
        {
        }
        #endregion

        protected override bool PreCombine(int count, System.Text.StringBuilder builder, IToken token)
        {
            Antlr.Runtime.CommonToken t = token as Antlr.Runtime.CommonToken;
            if (t != null)
            {
                if (this.TokenStartIndex <= 0)
                {
                    this.TokenStartIndex = t.StartIndex;
                }
                if (t.StopIndex > this.TokenStopIndex)
                {
                    this.TokenStopIndex = t.StopIndex;
                }
            }
            if (count > 0) builder.Append(" ");
            return true;
        }

        public override Expression DupNode()
        {
            return new GroupByClause(this);
        }

        public override void VisitSql(ISqlVisitor visitor)
        {
            visitor.Sql(this.ToString()); //GROUP BY keyword
            visitor.Space();
            for (int i = 0; this._children != null && i < this._children.Count; i++)
            {
                if (i != 0 && !Having.IsHaving(this._children[i])) visitor.Sql(",");
                else if (Having.IsHaving(this._children[i])) visitor.Space();
                this._children[i].VisitSql(visitor);
            }
        }
        public static bool IsGroupByClause(Expression exp)
        {
            if (exp == null || exp.IsNil) return false;
            return exp.Token.Type == OQLParser.GroupByClause;
        }
    }
}
